package com.baidu.health.service;

import com.baidu.health.mapper.TbGoodsMapper;
import com.baidu.health.mapper.TbOrderItemMapper;
import com.baidu.health.pojo.Cart;
import com.baidu.health.pojo.TbGoods;
import com.baidu.health.pojo.TbOrderItem;

import com.baidu.health.util.ResultResponse;
import com.baidu.health.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class CartService {

    private static  final String CART_LIST = "cartList";
    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    private TbGoodsMapper tbGoodsMapper;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    public ResultResponse addToCart(Integer goodsId ){
        TbGoods goods = tbGoodsMapper.selectById(goodsId);
        TbOrderItem tbOrderItem = new TbOrderItem();
        tbOrderItem.setGoodsId(goodsId);
        BigDecimal goodsPrice = goods.getGoodsPrice();
        System.out.println("商品价格打印"+goodsPrice);
        tbOrderItem.setPrice(goodsPrice);
        tbOrderItem.setTotalFee(goodsPrice);
        IdWorker idWorker = new IdWorker();
        long orderId = idWorker.nextId();
        tbOrderItem.setOrderId(orderId);
//        orderItem.setPrice(goods.getGoodsPrice());
        tbOrderItemMapper.insert(tbOrderItem);
        return ResultResponse.SUCCESS();
    }

    private Cart mergeCart(Cart oldCart, TbOrderItem orderItem){
        Cart newCart = new Cart();

        boolean isNotExistInOldCart = true;
        for (TbOrderItem oldOrderItem : oldCart) {
            if(oldOrderItem.getGoodsId().equals(orderItem.getGoodsId())) {//已经存在
                orderItem.setNum(oldOrderItem.getNum() + orderItem.getNum());
                orderItem.setTotalFee(orderItem.getPrice().multiply(
                        new BigDecimal(orderItem.getNum())
                ));
                if (orderItem.getNum() > 0) {
                    newCart.add(orderItem);
                }
                isNotExistInOldCart = false;
            }else{
                if(oldOrderItem.getNum()>0){
                    newCart.add(oldOrderItem);
                }
            }
        }
        if(isNotExistInOldCart){
            if(orderItem.getNum()>0){
                newCart.add(orderItem);
            }
        }

        return newCart;
    }



    public void resetCart(String userid, Cart newCart){
        redisTemplate.opsForHash().put(CART_LIST, userid,newCart);
    }
}
